#!/bin/sh
# Depend on the rdesktop package
#
# Copyright 2007, Led <ledest@gmail.com>
# 
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License with your
# Debian GNU system, in /usr/share/common-licenses/GPL.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

Message()
{
Result=4
while [ $Result -gt 3 ]; do
if which dialog >/dev/null 2>&1; then
    dialog --title "$1" \
	--extra-button \
	--ok-label 'Retrive' \
	--extra-label 'Reboot' \
	--cancel-label 'Power Off' \
	--yesno "$2" 10 64
    Result=$?
    clear
else
    clear
    echo "$1:"
    echo "$2"
    echo "Repeate / reBoot / Power Off (R/B/P) [R]"
    read A
    case $A in
	''|R|r) Result=0 ;;
	B|b) Result=3 ;;
	P|p) Result=1 ;;
	*) Result=4 ;;
    esac
    clear
fi
done
[ $Result -eq 1 ] && /sbin/poweroff
case $Result in
    1) /sbin/poweroff ;;
    3) /sbin/reboot ;;
esac
return $Result
}

. /usr/share/ltsp/ltsp_config

tty=$(tty)
case "$tty" in
  /dev/tty*) # with udev (2.6 kernel)
      ttynum=${tty#/dev/tty}
      ;;
  /dev/vc/*) # with devfs (2.4 kernel)
      ttynum=${tty#/dev/vc/}
      ;;
esac
displaynum=$(($ttynum - 1))

MAX_TIMEOUT=30
MAX_COUNT=5
COUNTER=0
FLAG=1
while [ $FLAG -ne 0 ]; do
    START_TIME=$(date +%s)
    RDESKTOP_OUTPUT=`xinit /usr/share/ltsp/screen.d/rdpx -- :$displaynum vt${ttynum} 2>&1 | grep '^ERROR:'`
    FINISH_TIME=$(date +%s)
    TIMEOUT=$((FINISH_TIME-START_TIME))
    if [ $TIMEOUT -le $MAX_TIMEOUT ]; then
	if [ $COUNTER -ge $MAX_COUNT ]; then
	    COUNTER=0
	    Message rdesktop "$RDESKTOP_OUTPUT" || FLAG=0
	else
	    COUNTER=$((COUNTER+1))
	fi
    else
	COUNTER=0
    fi
done
